<?php

namespace app\common\lib;

class Arr
{
    /**
     * 树状数据，支持无限极分类
     */
    public static function getTree($data,$pid='pid',$child='child',$select='perms',$selectData=[]): array
    {
        $items = [];
        foreach ($data as $v) {
            $items[$v['id']] = $v;
        }
        $tree = [];
        foreach ($items as $id => $item) {
            $items[$id]['checked']=false;
            if(isset($item[$select])&&in_array($item[$select],$selectData)){
                $items[$id]['checked']=true;
            }
            if (isset($items[$item[$pid]])) {
                $items[$item[$pid]][$child][] = &$items[$id];
            } else {
                $tree[] = &$items[$id];
            }
        }
        return $tree;
    }

    public static function toNumber($data){
        foreach ($data as $k=>$v){
            $data[$k]=$v*1;
        }
        return $data;
    }

    //二维数组根据指定字段排序
    public static function twoArraySortByField($array,$field,$sort){
        $sortBasis = $sort == 'asc' ? SORT_ASC : SORT_DESC;

        $last_field = array_column($array,$field);
        array_multisort($last_field,$sortBasis,$array);
        return $array;
    }

    /**
     * 生成指定字典（键值对）
     * @param $list
     * @param $fields - 逗号分隔字段
     * @param $key
     * @param $type - 1为累加 2为push
     * @return array
     */
    public static function getKeyValueByTwoArray($list,$fields,$key,$type){
        $arr = [];

        if (!empty($list)){
            $fields = explode(',',$fields);
            if($type == 1){
                foreach ($list as $k=>$v){
                    $num = 0;
                    for ($i=0;$i<count($fields);$i++){
                        $num += $v[$fields[$i]];
                    }
                    $arr[$v[$key]] = $num;
                }
            }else{
                foreach ($list as $k=>$v){
                    $arr[$v[$key]] = $v;
                }
            }
        }
        return $arr;
    }
}
